package org.heart.controller.message;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.util.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.heart.common.CommonResult;
import org.heart.entity.dto.FriendRelationship;
import org.heart.entity.dto.Message;
import org.heart.entity.dto.UserMessage;
import org.heart.entity.req.MessageReq;
import org.heart.entity.resp.GetMessageDetailsResp;
import org.heart.entity.resp.GetMessageListResp;
import org.heart.service.IFriendRelationshipService;
import org.heart.service.IMessageService;
import org.heart.service.IUserMessageService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.heart.common.enums.MessageTypeEnum.*;

/**
 * <p>
 * 消息主表 前端控制器
 * </p>
 *
 * @author lml
 * @since 2025-06-29
 */
@RestController
@RequestMapping("/message")
@Slf4j
public class MessageController {

    @Resource
    private IMessageService iMessageService;

    @Resource
    private IUserMessageService imMessageService;

    @Resource
    private IFriendRelationshipService iFriendRelationshipService;

    /**
     * 发送消息
     *
     * 类型：天气提醒
     *
     * 作用：接受用户ID为-1推送给所有关注用户，反之推送给相应用户
     */
    @PostMapping("/send")
    public CommonResult<String> sendMessage(@RequestBody MessageReq messageReq){

        //TODO: 这里需要补充添加消息推送的 成功性 判断
        if(messageReq.getMessageType().equals(TIAN_QI_REMINDER_MESSAGE_TYPE.getValue())){
            //处理天气提醒
            recordBatchAdd(messageReq,TIAN_QI_REMINDER_MESSAGE_TYPE.getValue());
        } else if(messageReq.getMessageType().equals(SYSTEM_NOTICE_MESSAGE_TYPE.getValue())){
            //处理系统通知
            recordBatchAdd(messageReq,SYSTEM_NOTICE_MESSAGE_TYPE.getValue());
        } else if(messageReq.getMessageType().equals(DING_YUE_REMINDER_MESSAGE_TYPE.getValue())){
            //处理订阅通知
            recordBatchAdd(messageReq,DING_YUE_REMINDER_MESSAGE_TYPE.getValue());
        }

        return CommonResult.successResponse("消息推送成功！");
    }

    /**
     * 处理批量推送 or 精准推送
     */
    public void recordBatchAdd(MessageReq messageReq,String messageType){

        if(messageReq.getAcceptId().equals("-1")){
            //推送给用户关注全部用户
            List<FriendRelationship> list = iFriendRelationshipService.getFriendList(messageReq.getUserId());

            for(FriendRelationship item: list){
                recordAdd(messageReq,messageType,item.getFriendId());
            }
        }else{
            //推送给指定用户
            recordAdd(messageReq,messageType,messageReq.getAcceptId());
        }
    }
    /**
     * 处理消息记录 - 用户消息记录 新增
     * 作用: 兼容批量新增消息记录
     */
    public void recordAdd(MessageReq messageReq,String messageType,String acceptId){
        Message message = new Message();
        BeanUtils.copyProperties(messageReq,message);
        message.setSendTime(new Date());//发送时间
        message.setTitle(messageType);//标题
        message.setSendType(messageType);//消息类型

        iMessageService.save(message);

        if(!ObjectUtil.isNull(message.getId())){
            UserMessage userMessage = new UserMessage();
            BeanUtils.copyProperties(messageReq,userMessage);
            userMessage.setMessageId(message.getId());
            userMessage.setAcceptId(acceptId);
            imMessageService.save(userMessage);
        }else{
            log.info("消息插入失败！");
        }
    }

    /**
     * 查询消息记录
     */
    @GetMapping("/getMessageList")
    private CommonResult<List<GetMessageListResp>> getMessageList(
            @RequestParam(value = "userId",required = false) String userId){

        if(StringUtils.isEmpty(userId)){
            return CommonResult.errorResponse("userId不能为空！");
        }

        QueryWrapper<UserMessage> qw = new QueryWrapper<>();
        qw.eq("accept_id",userId);
        List<UserMessage> list = imMessageService.list(qw);

        List<GetMessageListResp> resp = new ArrayList<>();
        for(UserMessage item: list){
            GetMessageListResp resps = new GetMessageListResp();

            Message message = iMessageService.getById(item.getMessageId());
            BeanUtils.copyProperties(message,resps);
            resps.setSendTime(DateUtils.format(message.getSendTime(),"yyyy-MM-dd HH:mm:ss"));
            resps.setReadStatus(item.getReadStatus());

            resp.add(resps);
        }

        return CommonResult.successResponse(resp);
    }

    /**
     * 修改消息状态： 由已读转换为未读
     */
    @GetMapping("/updateState")
    public CommonResult<String> updateState(@RequestParam(value = "id",required = false) Integer id){
        if(ObjectUtil.isNull(id)){
            return CommonResult.errorResponse("id 不能为空！");
        }

        QueryWrapper<UserMessage> qw = new QueryWrapper<>();
        qw.eq("message_id",id);
        List<UserMessage> list = imMessageService.list(qw);

        if(ObjectUtil.isNotNull(list) && list.size() > 0){
            UserMessage data = list.get(0);
            data.setReadStatus(1);
            data.setReceiveTime(new Date());
            imMessageService.updateById(data);
        }

        return CommonResult.successResponse("操作成功！");
    }

    /**
     * 查询消息详情
     */
    @GetMapping("/getData")
    public CommonResult<GetMessageDetailsResp> getData(@RequestParam(value="id",required = false) Integer id){

        if(ObjectUtil.isNull(id)){
            return CommonResult.errorResponse("id 不能为空！");
        }

        QueryWrapper<UserMessage> qw = new QueryWrapper<>();
        qw.eq("message_id",id);
        List<UserMessage> list = imMessageService.list(qw);

        UserMessage data = list.get(0);

        System.out.println("data====");
        System.out.println(data);

        Message message = iMessageService.getById(data.getMessageId());

        GetMessageDetailsResp info = new GetMessageDetailsResp();
        BeanUtils.copyProperties(message,info);
        BeanUtils.copyProperties(data,info);

        info.setSendTime(DateUtils.format(message.getSendTime(),"yyyy-MM-dd HH:mm:ss"));
        info.setReceiveTime(DateUtils.format(data.getReceiveTime(),"yyyy-MM-dd HH:mm:ss"));
        info.setId(Long.valueOf(id));

        return CommonResult.successResponse(info);

    }
}
